
// 分割数组
export function splitArr (arr, size) {
  const tempArr = []
  for (let i = 0; i < arr.length; i += size) {
    tempArr.push(arr.slice(i, i + size))
  }
  return tempArr
}

// 下划线转换驼峰
export function toHump (name) {
  return name.replace(/_(\w)/g, (all, letter) => {
    return letter.toUpperCase()
  })
}
// 驼峰转换下划线
export function toLine (name) {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase()
}

// 是否加载某个js
export function isHaveFile (name) {
  const jsArr = [...document.getElementsByTagName('script')]
  return jsArr.some(ele => ele.src.indexOf(name) > -1)
}

/**
 * 解决js计算精度问题 f:计算的价格 如: CalculationPrice(0.1+0.2)
 */
export function CalculationPrice (f) {
  const num = Math.round(f * 100)
  return num / 100
}

/**
 * 判断是否外部链接
 * @param {string} path 路径
 */
export function isExternal (path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

// JS复制
export function copyContent (content) {
  const oInput = document.createElement('input')
  oInput.value = content
  oInput.readOnly = 'readOnly' // 防止ios聚焦触发键盘事件
  oInput.style.position = 'absolute'
  oInput.style.left = '-1000px'
  oInput.style.zIndex = '-1000'
  document.body.appendChild(oInput)
  oInput.select()
  if (!document.execCommand('copy')) {
    oInput.setSelectionRange(0, oInput.value.length)
    document.execCommand('Copy')
  } else {
    document.execCommand('copy')
  }
  // oInput.style.display = 'none'
  document.body.removeChild(oInput)
  return true
}

// 解析URL参数 返回一个对象
export function urlParse (url = window.location.search) {
  // let url = window.location.search
  const obj = {}
  const reg = /[?&][^?&]+=[^?&]+/g
  const arr = url.match(reg)
  // ['?id=12345','&a=b']
  if (arr) {
    arr.forEach((item) => {
      const tempArr = item.substr(1).split('=')
      const key = decodeURIComponent(tempArr[0])
      const val = decodeURIComponent(tempArr[1])
      obj[key] = val
    })
  }
  return obj
}

/**
 * 删除`url`中的指定参数
 * @param {string | Array<string>} names
 * @param {string} url
 */
export function urlDel (names, url) {
  if (typeof (names) === 'string') {
    names = [names]
  }
  const loca = url || window.location
  const obj = {}
  const arr = loca.search.substr(1).split('&')
  // 获取参数转换为object
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i].split('=')
    obj[arr[i][0]] = arr[i][1]
  }
  // 删除指定参数
  for (let i = 0; i < names.length; i++) {
    delete obj[names[i]]
  }
  // 重新拼接url
  const urls = loca.origin + loca.pathname + '?' + JSON.stringify(obj).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')
  return urls
}
